import socket
import json

class RedisClient:
    def __init__(self, host='127.0.0.1', port=6379):
        self.host = host
        self.port = port
        self.socket = None

    def connect(self):
        """连接到服务器"""
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((self.host, self.port))

    def _send_command(self, command):
        """发送命令到服务器"""
        self.socket.send(json.dumps(command).encode('utf-8'))
        response = self.socket.recv(1024).decode('utf-8')
        return json.loads(response)

    def set(self, key, value, ex=None):
        """设置键值对"""
        command = {
            'type': 'set',
            'key': key,
            'value': value,
            'expiry': ex
        }
        return self._send_command(command)

    def get(self, key):
        """获取值"""
        command = {
            'type': 'get',
            'key': key
        }
        return self._send_command(command)

    def delete(self, key):
        """删除键"""
        command = {
            'type': 'delete',
            'key': key
        }
        return self._send_command(command)

    def hset(self, name, key, value):
        """哈希表设置"""
        command = {
            'type': 'hset',
            'key': name,
            'hash_key': key,
            'value': value
        }
        return self._send_command(command)

    def hget(self, name, key):
        """哈希表获取"""
        command = {
            'type': 'hget',
            'key': name,
            'hash_key': key
        }
        return self._send_command(command)

    def close(self):
        """关闭连接"""
        if self.socket:
            self.socket.close()
